package friot.service.cloud.config.mqtt;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import friot.model.iot.entity.IotThings;
import friot.service.cloud.service.IotThingsService;
import friot.utils.constants.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author He Kuntao
 * @desc MQTT统一消息入口
 * @date 2024/2/11 13:19
 */
@Slf4j
@Component
public class MqttMessageHandler implements MessageHandler {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IotThingsService iotThingsService;


    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        log.info("MQTT消息处理：{}", message);
        String topic = message.getHeaders().get("mqtt_receivedTopic", String.class);
        if (StringUtils.isBlank(topic)) {
            return;
        }
        String[] topicArr = topic.split("/");
        handlerMqttMessage(topicArr[2], topicArr[3], (String) message.getPayload());
    }

    private void handlerMqttMessage(String modelId, String deviceId, String payload) {
        // 判断设备是否存在
        Boolean member = stringRedisTemplate.opsForSet().isMember(RedisConstants.CLOUD_DEVICE_IDS, deviceId);
        if (!Boolean.TRUE.equals(member)) {
            log.error("设备不存在：{}", deviceId);
            return;
        }

        // 获取设备数据
        HashMap hashMap = JSON.parseObject(payload, HashMap.class);
        hashMap.forEach((k, v) -> {
            Boolean isMember = stringRedisTemplate.opsForSet()
                    .isMember(RedisConstants.CLOUD_DEVICE_MODEL + modelId, k);
            if (Boolean.TRUE.equals(isMember)) {
                log.info("对口数据:{} : {}", k, v);
                // save
                IotThings iotThings = new IotThings();
                iotThings.setDeviceId(deviceId);
                iotThings.setIdentified(k.toString());
                iotThings.setUpValue(v.toString());
                iotThingsService.save(iotThings);
            }
        });
    }
}
